<?php
/**
 * Created by PhpStorm.
 * User: gogo
 * Date: 2019/2/22
 * Time: 下午5:33
 */
namespace app\model;


use think\Db;

class Customer extends BaseModel
{

    static function updateOrCreate($data){

        $info = db('customer')->where(['openid'=> $data['openid']])->field('id, status, nickname, avatar_url')->find();
        if($info){
            $id = $info['id'];
            db('customer')->where(['id'=> $id])->update($data);
            if($info['status'] != 1){
                exit(fail('ACCOUNT_IS_FROZEN'));
            }
            $is_new = 0;

        }else{
            $id = db('customer')->insertGetId($data);
            $is_new = 1;
        }

        $data['id'] = $id;
        $data['is_new'] = $is_new;
        $data['nickname'] = isset($info["nickname"]) ? $info["nickname"] : '';
        $data['avatar_url'] = isset($info["avatar_url"]) ? $info["avatar_url"] : '';
        return $data;

    }

    static function add_money($data){

        $u_id = $data['u_id'];
        $parent_id = $data['parent_id'];
        $is_new = $data['is_new'];

        if($is_new){
//            $type = 1;
//            $field = 'money';
//            $value = 0.3;
            $type = 2;
            $field = 'tiger_tee';
            $value = 30;
            $reason_type = 12;
        }else{
//            $type = 2;
//            $field = 'tiger_tee';
//            $value = 50;
        }

        $status = false;

        Db::startTrans();

        try{

            \db('master_log')->insert([
               'u_id'=> $u_id,
               'parent_id'=> $parent_id,
               'is_new'=> $is_new,
               'create_time'=> date('Y-m-d')
            ]);
            \db('customer')->where(['id'=> $parent_id])->setInc($field, $value);
            MoneyLog::addLog([
                'u_id'=> $parent_id,
                'type'=> $type,
                'value'=> $value,
                'reason_type'=> $reason_type,
                'child_id'=> $u_id,
            ]);

            $status = true;

            Db::commit();

        }catch (\Exception $exception){
//            echo $exception->getMessage();
            Db::rollback();
        }

        return $is_new && $status;


    }

}